package com.fast.framework.web.service;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.log.Log;
import com.fast.framework.core.domain.User;
import com.fast.framework.core.service.IUserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Log log = Log.get(UserDetailsServiceImpl.class);

    @Resource
    private IUserService userService;

    @Resource
    private RoleService roleService;

    /**
     * 根据用户名查找用户
     *
     * @param username 用户名
     * @return 用户
     * @throws UsernameNotFoundException 用户不存在异常
     */
    @Override
    public User loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.selectUserByUserName(username);
        if (ObjUtil.isEmpty(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new RuntimeException("user.not.exists");
        } else if (!user.isEnabled()) {
            log.info("登录用户：{} 已被删除.", username);
            throw new RuntimeException("user.password.delete");
        }
        user.setRoles(roleService.getRolesBtUserId(user.getUserId()));
        return user;
    }
}
